﻿#if UNITY_PURCHASING
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
using System.Text;
using UnityEngine.UI;

namespace Brainagi.BrainMachine{
	public class UnlockPurchaser {
		//public const string ProductID = "unlcok_all";
		public const string ProductID = "buy_gold_001";
		public static IAPButton unlockButton{ get; private set;}

		public static IAPButton CreateUnlockButton(){
			IAPButton button = new GameObject ("UnlockButton").AddComponent<IAPButton> ();
			button.productId = ProductID;
			button.GetComponent<Button> ().interactable = false;
			button.onPurchaseComplete = new IAPButton.OnPurchaseCompletedEvent ();
			button.onPurchaseFailed = new IAPButton.OnPurchaseFailedEvent ();
			button.onPurchaseComplete.AddListener (OnPurchaseCompleted);
			button.onPurchaseFailed.AddListener (OnPurchaseFailed);
			button.consumePurchase = false;
			unlockButton = button;
			return button;
		}

		public static void Purchase(){
			if (unlockButton != null) {
				unlockButton.GetComponent<Button> ().onClick.Invoke ();
			} else {
				Debug.LogError ("The Unlock IAPButton hasn't created!");
			}
		}

		static void OnPurchaseCompleted(Product p){
			StringBuilder sb = new StringBuilder ("Product:");
			sb.AppendFormat ("\n availableToPurchase: {0}", p.availableToPurchase);
			sb.AppendFormat ("\n definition: {0}", p.definition);
			sb.AppendFormat ("\n definition.id: {0}", p.definition.id);
			sb.AppendFormat ("\n definition.storeSpecificId: {0}", p.definition.storeSpecificId);
			sb.AppendFormat ("\n definition.type: {0}", p.definition.type);
			sb.AppendFormat ("\n hasReceipt: {0}", p.hasReceipt);
			sb.AppendFormat ("\n metadata: {0}", p.metadata);
			sb.AppendFormat ("\n metadata.isoCurrencyCode: {0}", p.metadata.isoCurrencyCode);
			sb.AppendFormat ("\n metadata.localizedDescription: {0}", p.metadata.localizedDescription);
			sb.AppendFormat ("\n metadata.localizedPrice: {0}", p.metadata.localizedPrice);
			sb.AppendFormat ("\n metadata.localizedPriceString: {0}", p.metadata.localizedPriceString);
			sb.AppendFormat ("\n metadata.localizedTitle: {0}", p.metadata.localizedTitle);
			sb.AppendFormat ("\n receipt: {0}", p.receipt);
			sb.AppendFormat ("\n transactionID: {0}", p.transactionID);
			Debug.Log (sb.ToString ());
			unlockButton.consumePurchase = true;
		}

		static void OnPurchaseFailed(Product p, PurchaseFailureReason reason){
			Debug.LogFormat ("Purchase failed: {0}, reason: {1}", p, reason);
		}
	}
}
#endif